package com.java.base.io.aio;

import com.java.base.io.nio.NIOServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AIOSocket {
    static Logger logger = Logger.getLogger(NIOServer.class.getSimpleName());

    static {
        logger.setLevel(Level.INFO);
    }

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 0xcccc)).get();

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        socketChannel.read(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                attachment.flip();
                logger.info(Thread.currentThread().getName() + " 收到：" + new String(attachment.array(), 0, result));
                attachment.clear();
                socketChannel.read(byteBuffer, byteBuffer, this);
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                logger.throwing("", "", exc);
            }
        });

        send(socketChannel);

    }

    public static void send(AsynchronousSocketChannel socketChannel) throws IOException {
        Scanner scanner = new Scanner(System.in);
        logger.info("输入：");
        while (socketChannel.isOpen()) {
            String s = scanner.nextLine();
            if (s.equals("stop")) {
                logger.info("结束程序");
                socketChannel.close();
                break;
            }
            socketChannel.write(ByteBuffer.wrap(s.getBytes(StandardCharsets.UTF_8)));
        }

    }
}
